<!-- 活动类型管理 -->
<template>
  <page-header-wrapper>
    <a-card class="table-card">
      <GzSearchForm :searchFunc="searchFunc" :resetFunc="()=>{ searchData = {} }">
        <!-- <GzTextUp placeholder="活动类型ID" v-model:value="searchData['activityTypeId']"/> -->
        <GzTextUp v-model:value="searchData['goodsName']" placeholder="商品名称" />
        <a-form-item class="table-search-item">
          <a-select v-model:value="searchData['type']" :placeholder="'商品类型'">
            <a-select-option :value="0">卡密商品</a-select-option>
            <a-select-option :value="1">代充商品</a-select-option>
          </a-select>
        </a-form-item>
      </GzSearchForm>
  
      <!-- 列表渲染 -->
      <GzTable
        ref="infoTableRef"
        :init-data="true"
        :req-table-data-func="reqTableDataFunc"
        :table-columns="tableColumns"
        :search-data="searchData"
        row-key="activityTypeId"
        :scrollX="0"
      >
        <!-- <template #topBtnSlot>
            <a-button v-if="$access('ENT_ACTIVITY_TYPE_INFO_ADD')" type="primary" @click="addOrEditFunc(false)">
              <plus-outlined />新建
            </a-button>
          </template> -->
  
        <template #bodyCell="{ column, record }">
          <template v-if="column.key == 'goodsImgBanner'">
            <a-image :src="record.goodsImgBanner" /> 
          </template>
          <template v-if="column.key == 'goodsImgListSmall'">
            <a-image :src="record.goodsImgListSmall" />  
          </template>
          <template v-if="column.key == 'goodsImgListBig'">
            <a-image :src="record.goodsImgListBig" />
          </template>
          <template v-if="column.key == 'goodsPrice'">
            <!-- marketPrice 分转换成元 -->
            <template v-if="record.goodsPrice">{{ record.goodsPrice/100 }}</template>
          </template>
          <template v-if="column.key == 'marketPrice'">
            <!-- marketPrice 分转换成元 -->
            <template v-if="record.marketPrice">{{ record.marketPrice/100 }}</template>
          </template>
          <template v-if="column.key == 'type'">
            <template v-if="record.type == 0">卡密商品</template>
            <template v-if="record.type == 1">代充商品</template>
          </template>
          <template v-if="column.key == 'operation'">
            <a-button v-if="$access('ENT_VIRTUAL_INNER_EDIT')" type="link" @click="addOrEditFunc(record)">修改</a-button>
            <a-button v-if="$access('ENT_VIRTUAL_INNER_ALLOC') && record.type ==0" type="link" @click="transferFun(record)">划拨</a-button>
            <a-upload      
              v-if="$access('ENT_VIRTUAL_INNER_IMPT') && record.type ==0"
              v-model:file-list="fileList"   
              name="file"
              :maxCount="1"
              accept=".xlsx, .xls"
              :data="formParams"
              :action="action" 
              :showUploadList="false"
              :beforeUpload="beforeUpload" 
              @change="uploadChange"
            >
              <span style="color:#1890ff ;" @click="exportData(record)">导入CDK</span>
            </a-upload>
          </template>
        </template>
      </GzTable>
    </a-card>
    <!-- 新增OR修改 -->
    <AddOrEdit ref="addOrEditRef" :callBackFunc="searchFunc" />
      
    <template>
      <a-drawer v-model:visible="visibleTransfer" :maskClosable="false" title="划拨内部商品" width="40%">
        <a-form
          ref="formRef"
          :model="transferObject"
          layout="vertical"
          labelAlign="left"
          :rules="transferTules"
          :colon="false"
          :wrapper-col="{ span: 24 }"
          style="margin-top: 30px; margin-left: 20px"
        >
          <a-row>
            <a-col :span="8">
              <span>总数量：{{ transferObject.total }}</span>
            </a-col>
            <a-col :span="8">
              <span>已划拨数量：{{ transferObject.usedNum }}</span>
            </a-col>
            <a-col :span="8">
              <span>未划拨数量：{{ transferObject.unusedNum }}</span>
            </a-col>
          </a-row>

          <a-row style="margin-top: 20px;">
            <a-col :span="11">
              <a-form-item label="机构" name="agentNo">
                <!-- <a-select ref="select" v-model:value="transferObject['agentNo']" style="width: 100%" placeholder="请选择机构"> 
                  <a-select-option v-for="(item, index) in ruleListProduct" :key="index" :lable="item.agentName " :value="item.agentNo">
                    {{ item.agentName }}
                  </a-select-option>
                </a-select> -->
                <GzTreeSelect ref="gzThreeRef" v-model:value="transferObject['agentNo']" />
              </a-form-item>
            </a-col>
            <a-col :push="1" :span="11">
              <a-form-item label="划拨数量" name="num">
                <a-input-number
                  v-model:value="transferObject['num']"
                  placeholder="请输入划拨数量"
                  :precision="0"
                  min="0"
                  style="width: 100%"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>

        <!-- 列表渲染 -->
        <GzTable
          v-if="visibleTransfer"
          ref="infoTableTransferRef"
          :init-data="true"
          :req-table-data-func="reqTableDataTransferFunc"
          :table-columns="tableColumnsTransfer"
          row-key="agentNo"
          :scrollX="0"
        >
          <template #bodyCell="{ column, record }" />
        </GzTable>

        <div class="drawer-btn-center">
          <a-button :style="{ marginRight: '8px' }" style="margin-right: 8px" @click="onClose">
            <close-outlined />
            取消
          </a-button>
          <a-button type="primary" :loading="transferLoading" @click="handleOkFunc">
            <check-outlined />
            保存
          </a-button>
        </div>
      </a-drawer>
    </template>
  </page-header-wrapper>
</template>
  
  <script lang="ts" setup>
  import AddOrEdit from './AddOrEdit.vue'
  // import { req, API_URL_VIRTUAGOODS_INSIDE, $transferGoods,$getAgentList,API_URL_VIRTUALGOODS_INSIDE_SAVE } from '@/api/manage'
  import {$apiVirtualGoodsInside,$apiVirtualGoodsInsideSaveCdkNum,$transferGoods,$getAgentList,$getUploadFormParams,$apiVirtualAwardCdkImportCdk,$getUsedCdkList} from '@/api/externalGoods/innertable/index'
  import { ref, reactive, getCurrentInstance } from 'vue'
  
  const { $infoBox, $access } = getCurrentInstance()!.appContext.config.globalProperties
  
  const fileList = ref([])
  const action = ref() as any
  const formParams = ref() as any
  const ossFileUrl = ref() as any
  const infoTableRef = ref()
  const addOrEditRef = ref()
  const virtualInsideId = ref('')
  
  const tableColumns = reactive([
    { key: 'goodsName', title: '商品名称',dataIndex: 'goodsName' },
    { key: 'goodsImgListSmall', title: '商品图片--列表小图',dataIndex: 'goodsImgListSmall' },
    { key: 'goodsImgListBig', title: '商品图片--列表大图',dataIndex: 'goodsImgListBig' },
    { key: 'goodsPrice', title: '商品进价（元）',dataIndex: 'goodsPrice' },
    { key: 'marketPrice', title: '市场价（元）',dataIndex: 'marketPrice' },
    { key: 'type', title: '商品类型',dataIndex: 'type' },
    { key: 'remark', title: '备注', dataIndex:'remark' },
    { key: 'operation', title: '操作', dataIndex: 'operation', align: 'center' ,width: 180 }
  ])
  const searchData:any = ref({})
  const infoTableTransferRef = ref()
  // 请求table接口数据
  function reqTableDataFunc(params: any) {
      return  $apiVirtualGoodsInside(params)
  }
 
const tableColumnsTransfer = reactive([
    { key: 'agentNo', title: '机构号',dataIndex: 'agentNo' },
    { key: 'agentName', title: '机构名称',dataIndex: 'agentName' },
    { key: 'cdkCount', title: '数量',dataIndex: 'cdkCount' },
])
  
  function searchFunc() {
    infoTableRef.value.refTable(true)
  }
  // 新增OR修改
  function addOrEditFunc(record:any){
    addOrEditRef.value.show(record)
  }
  const ruleListProduct = ref([]) as any 
  const visibleTransfer = ref(false) as any 
const transferLoading = ref(false) as any 
const transferObject = ref({}) as any
const transferTules = {
  agentNo: [
    { required: true, message: '机构不能为空', trigger: 'change' }, 
  ],
  num: [
    { required: true, message: '请输入划拨数量', trigger: 'change' }, 
  ]
}

// 导入数据
const exportData = (record) =>{
  virtualInsideId.value = record.virtualInsideId
}

/**
 * 文件上传
 */
 function beforeUpload(file) {
  // 校验文件大小 不大于20MB
  const isLt20M = file.size / 1024 / 1024 < 20
  if (!isLt20M) {
    $infoBox.message.warn('文件大小不能超过20MB！')
    return false
  }
  // 校验文件格式
  const isExcel = /\.(xlsx|xls)$/.test(file.name)
  if (!isExcel) {
    $infoBox.message.warn('文件格式必须为XLS/XLSX！')
    return false
  }
  return $getUploadFormParams(file, 'upload').then(res => {
    action.value = res.formActionUrl // action 
    formParams.value = res.formParams //表单组件 
    ossFileUrl.value = res.ossFileUrl
  })
}
function uploadChange(info) {
 
  if (info.file.status === 'error') { // 上传异常
    fileList.value = []
    $infoBox.message.error('上传异常,请联系系统管理员')
  } if (info.file.status === 'done') {
    // 上传成功
    complete()
  }
}

function complete() {
  const data ={
    // supplierId:supplierId.value,
    virtualInsideId:virtualInsideId.value,
    ossFileUrl:ossFileUrl.value
  }
  $apiVirtualAwardCdkImportCdk(data).then((res) => {    
          const failUrl = res
          if(res){
            const link = document.createElement('a')
            link.href = failUrl
            link.download = 'filename.xlsx' // 设置下载文件名
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
          }else{
            $infoBox.message.success('此次数据没有异常')
          }
          $infoBox.message.success('生成成功')
          infoTableRef.value.refTable(true)
    })
}

// 划拨
function transferFun(record:any){
    transferObject.value.virtualInsideId = record.virtualInsideId
  visibleTransfer.value = true
  $transferGoods({virtualInsideId:record.virtualInsideId}).then(res=>{
      transferObject.value = res
      // 重写给transferObject赋值virtualInsideId
      transferObject.value.virtualInsideId = record.virtualInsideId
  })
  reqTableDataTransferFunc()
}
   function reqTableDataTransferFunc(){
     return $getUsedCdkList({virtualInsideId:transferObject.value.virtualInsideId})
   }

const formRef = ref()
function handleOkFunc(){
  formRef.value.validate().then(() => {
  if(transferObject.value.num > transferObject.value.unusedNum){
    $infoBox.message.error('划拨数量不能大于未划拨数量！')
    return false
  }
  transferLoading.value = true  
  $apiVirtualGoodsInsideSaveCdkNum({ ...transferObject.value}).then(res=>{
        $infoBox.message.success('保存成功！')
        onClose()
        transferLoading.value= false
      }).catch(()=>{
        transferLoading.value = false
      })
  }).catch(() => {})


}
  function onClose(){
    visibleTransfer.value = false
    formRef.value.resetFields()
  }
  </script>
  <style lang="less" scoped>
  :deep(img){
    width: 80px;
    height: 80px;
    object-fit: cover;
  }
  </style>
  